package com.springinaction.ch05.web;

import com.springinaction.ch05.Spitter;
import com.springinaction.ch05.data.SpitterRepository;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;


/**
 * @author ssk
 * @Title: SpitterController
 * @ProjectName SpringInAction
 * @Description: TODO
 * @date 18-12-9下午6:02
 */
@Controller
@RequestMapping(value = {"spitter"})
public class SpitterController {
    private SpitterRepository spitterRepository;
    @Autowired
    public SpitterController(SpitterRepository spitterRepository) {
        this.spitterRepository = spitterRepository;
    }
    @RequestMapping(value = {"/register"}, method = RequestMethod.GET)
    public String showRegistrationFrom() {
        return "registerForm";
    }
    @RequestMapping(value = {"register"}, method = RequestMethod.POST)
    public String processRegsitration(@Valid Spitter spitter, Errors errors) {
        if (errors.hasErrors()) {
            System.out.print(ArrayUtils.toString(errors.getAllErrors(), " , "));
            return "registerForm";
        }
        spitterRepository.save(spitter);
        return "redirect:/spitter/" + spitter.getUsername();
    }
    @RequestMapping(value = {"{username}"}, method = RequestMethod.GET)
    public String showSpitterProfile(
            @PathVariable String username, Model model
    ) {
        model.addAttribute(spitterRepository.findByUsername(username));
        return "profile";
    }
}
